function L = Berlekamp_Massey_algorithm(sequence)
    N = length(sequence);
    s = sequence;

    for k = 1:N
        if s(k) == 1
            break;
        end
    end

    f = [k + 1, 0];
    l = k + 1;

    g = [0];
    a = k;
    b = 0;

    for n = k + 1:N
        d = 0;
        for ele = f
            d = bitxor(d, s(ele + n - l));
        end

        if d == 0
            b = b + 1;
        else
            if 2 * l > n
                f = bitxor(f, g + (a - b));
                b = b + 1;
            else
                temp = f;
                f = bitxor(b - a + f, g);
                l = n + 1 - l;
                g = temp;
                a = b;
                b = n - l + 1;
            end
        end
    end

    L = l;
end
